<template>
  <div class="pf-flow-todo pf-bgwhite">
    <div>当前流程实例：{{ currentTodoTask.processInstId }}</div>
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane class="pf-mt-10" label="审批信息" name="flowInfo">
        <flow-approval-info
          ref="flowApprovalInfoDom"
          @commitDone="commitDone"
          :process-inst-id="currentTodoTask.processInstId"
          :start-form-key="startFormKey"
          :task-form-key="currentTodoTask.taskFormKey"
          :task-ins-id="currentTodoTask.taskInsId"
          :task-definition-key="currentTodoTask.taskDefinitionKey"
        ></flow-approval-info>
      </el-tab-pane>
      <el-tab-pane class="pf-mt-10" label="审批历史" name="flowHistory">
        <flow-approval-history
          :process-inst-id="currentTodoTask.processInstId"
        ></flow-approval-history>
      </el-tab-pane>
      <el-tab-pane class="pf-mt-10" label="流程图" name="flowDiagram">
        <div class="pf-flow-todo-canvas" ref="flowViewerRef"></div>
      </el-tab-pane>
      <el-tab-pane class="pf-mt-10" label="流程附件" name="flowFiles">
        <el-empty description="功能建设中"></el-empty>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script lang="ts">
import { defineComponent, nextTick, onMounted, Ref, ref, toRefs } from 'vue';
import FlowApprovalHistory from '@/views/page-config/flow/todos/FlowApprovalHistory.vue';
import { viewer } from '@/views/page-config/flow/flow-viewer';
import { ResponseCodeEnum, useHttpClient } from 'pf-component';
import { camundaApi } from '@/constants/api/camunda-api';
import { useNotice } from '@/components/element-plus/notice';
import FlowApprovalInfo from '@/views/page-config/flow/todos/FlowApprovalInfo.vue';

export default defineComponent({
  name: 'FlowTodo',
  components: { FlowApprovalInfo, FlowApprovalHistory },
  emits: ['commitDone'],
  props: ['todoTask'],
  setup(props, { emit }) {
    const currentTodoTask: Ref<any> = toRefs(props).todoTask;
    const nodeColor = { done: '#67C23A', running: '#409EFF', todo: '#303133' };
    const startFormKey = ref('');
    const flowApprovalInfoDom: Ref = ref(null);
    const activeTab: Ref<string> = ref('flowInfo');
    const handleTabClick = (data: any) => {};
    const flowViewerRef = ref(null);
    const setNodeColor = (nodes: string[], color: string) => {
      if (!viewer.getViewer() || !viewer.getViewer().get('canvas')) {
        return;
      }
      const modeling = viewer.getViewer().get('modeling');
      const elementRegistry = viewer.getViewer().get('elementRegistry');
      for (const nodeId of nodes) {
        const node = elementRegistry.get(nodeId);
        if (!node) {
          continue;
        }
        modeling.setColor(node, { stroke: color });
      }
    };
    const commitDone = (val: boolean) => {
      emit('commitDone', val);
    };
    onMounted(() => {
      viewer.init(flowViewerRef.value);
      useHttpClient()
        .general<string>(camundaApi.processFormApi.startFormKey, {
          processDefinitionId: currentTodoTask.value.processDefinitionId
        })
        .then(res => {
          if (ResponseCodeEnum.SUCCESS === res.code) {
            startFormKey.value = res.data;
            nextTick(() => {
              flowApprovalInfoDom.value.initFormConfig();
            });
          } else {
            useNotice().message.error(res.message);
          }
        });
      useHttpClient()
        .general<any>(camundaApi.processApi.getResource, {
          processDefinitionId: currentTodoTask.value.processDefinitionId
        })
        .then(res => {
          viewer.getViewer().importXML(res.data, (err: any) => {
            if (err) {
              console.error(err);
              return;
            }
            useHttpClient()
              .general<any[]>(camundaApi.processTaskApi.queryDoneNode, {
                id: currentTodoTask.value.processInstId
              })
              .then(res => {
                if (ResponseCodeEnum.SUCCESS === res.code) {
                  if (res.data && res.data.length > 0) {
                    const doneIds = [];
                    const runningIds = [];
                    for (const v of res.data) {
                      if (v.endTime) {
                        doneIds.push(v.activityId);
                      } else {
                        runningIds.push(v.activityId);
                      }
                    }
                    setNodeColor(doneIds, nodeColor.done);
                    setNodeColor(runningIds, nodeColor.running);
                  }
                } else {
                  useNotice().message.error(res.message);
                }
              });
          });
        });
    });
    return {
      activeTab,
      handleTabClick,
      flowViewerRef,
      commitDone,
      startFormKey,
      currentTodoTask,
      flowApprovalInfoDom
    };
  }
});
</script>
<style scoped lang="scss">
.#{$prefix} {
  &-flow-todo {
    //margin: 10px;
    //padding: 0;
    overflow-y: auto;
    height: calc(70vh - 50px);
    &-canvas {
      height: 400px;
    }
  }
}
</style>
